package cn.niit.smbmsdemo.interceptor;

import cn.niit.smbmsdemo.entity.User;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 *是否登录拦截器，主要拦截请求用户是否登录
 *
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println("LoginInterceptor.preHandle............." + handler);
        /**
         * 第一步：获取用户请求URL
         */
        Thread.sleep(500);
        String uri = request.getRequestURI();
        String url = request.getRequestURI().toString();
        System.out.println("uri: " + uri + " \t url:" + url);
        if(uri.equals("/login")){
            return true;
        }

        /**
         * 第二步：判断该请求是否需要拦截，或者说是否需要在登录情况下访问
         */
        User user = (User) request.getSession().getAttribute("user");
        if (null == user) {
            System.out.println("拦截器 LoginInterceptor 执行 preHandle 将 【" + uri + "】 已拦截，拦截原因：未登录！！！");
            //跳转至登陆页面 ?
            //request.getRequestDispatcher("/Login").forward(request, response);
            response.sendRedirect("/login");
            return false;
        }
        return true;
    }
        @Override
        public void postHandle (HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
        modelAndView) throws Exception {
            System.out.println("LoginInterceptor.postHandle++++++++++++++++++");
        }

        @Override
        public void afterCompletion (HttpServletRequest request, HttpServletResponse response, Object handler, Exception
        ex) throws Exception {
            System.out.println("LoginInterceptor.afterCompletion=============");
        }

    }
